package org.jeecg.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiMiddleCompany;
import org.jeecg.modules.manage.entity.CaishuiServiceCompany;
import org.jeecg.modules.manage.service.IMCaishuiBusinessService;
import org.jeecg.modules.manage.service.IMCaishuiMiddleCompanyService;
import org.jeecg.modules.manage.service.IMCaishuiServiceCompanyService;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 中台用户
 *
 * @Author scott
 * @since 2023-02-20
 */
@Api(tags="中台用户")
@Slf4j
@RestController
@RequestMapping("/sys/middle/user")
public class SysMiddleUserController {

	@Autowired
	private ISysUserService sysUserService;
    @Autowired
    private IMCaishuiServiceCompanyService imCaishuiServiceCompanyService;


	//==========================================================后台====================================================
    /**
     * 获取用户列表数据
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="中台用户-分页列表查询", notes="中台用户-分页列表查询")
    @GetMapping(value = "/list")
	public Result<IPage<SysUser>> queryPageList(SysUser user,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
		QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());

        //只查询中台用户
        queryWrapper.eq("user_type",2);
		Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
		IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}



    /**
     * 添加中台用户
     * @param user
     * @return
     */
    @AutoLog(value = "中台用户-添加")
    @ApiOperation(value="中台用户-添加", notes="中台用户-添加")
    @PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysUser user) {
        if (user.getMiddleOptAuth()==0 && oConvertUtils.isEmpty(user.getRelTenantIds()))  return Result.error("参数错误！");
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setPhone(user.getUsername());
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        user.setUserType(2);
        // 保存用户走一个service 保证事务
        sysUserService.saveUser(user, null);
		return Result.ok("添加成功！");
	}

    /**
     *  编辑
     *
     * @param user
     * @return
     */
    @AutoLog(value = "中台用户-编辑", dataType = 2)
    @ApiOperation(value="中台用户-编辑", notes="中台用户-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<?> edit(@RequestBody SysUser user) {
        user.setPhone(user.getUsername());
        sysUserService.editUser(user);
        return Result.OK("编辑成功!");
	}

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @GetMapping("/recycleBin")
    public Result getRecycleBin() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserType, 2);
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted(wrapper);
        return Result.ok(logicDeletedUserList);
    }

    /**
     * 查询中台用户绑定的公司ids
     * @param tenantId
     * @return
     */
    @GetMapping("/queryCompanyIds")
    public Result queryCompanyIds(@RequestParam(name="tenantId") String tenantId) {
        LambdaQueryWrapper<CaishuiServiceCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CaishuiServiceCompany::getId).eq(CaishuiServiceCompany::getTenantId, tenantId);
        String ids = "";
        CaishuiServiceCompany company = imCaishuiServiceCompanyService.getOne(wrapper);
        if(oConvertUtils.isNotEmpty(company)){
            ids = company.getId();
        }
        return Result.ok(ids);
    }
    //==========================================================后台====================================================

    //==========================================================中台====================================================
    /**
     * 获取用户列表数据
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="中台-用户管理-分页列表查询", notes="中台-用户管理-分页列表查询")
    @GetMapping(value = "/listMiddle")
    public Result<IPage<SysUser>> queryPageListMiddle(SysUser user,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        //查询当前租户下的中台用户
        queryWrapper.lambda().eq(SysUser::getUserType,2);
        queryWrapper.lambda().in(SysUser::getRelTenantIds, TokenUtils.getLoginUser().getRelTenantIds());
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @AutoLog(value = "中台-用户管理-添加")
    @ApiOperation(value="中台-用户管理-添加", notes="中台-用户管理-添加")
    @PostMapping(value = "/addMiddle")
    public Result<?> addMiddle(@RequestBody SysUser user) {
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setPhone(user.getUsername());
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        //用户表字段org_code不能在这里设置他的值
        user.setOrgCode(null);
        user.setUserType(2);
        user.setMiddleOptAuth(1);
        //当前登录用户
        LoginUser loginUser = TokenUtils.getLoginUser();
        user.setNickname(loginUser.getNickname());
        user.setAvatar(loginUser.getAvatar());
        user.setRelTenantIds(loginUser.getRelTenantIds());//保存当前登录用户的租户信息

        // 保存用户走一个service 保证事务
        sysUserService.saveUser(user, null);
        return Result.ok("添加成功！");
    }

    /**
     *  编辑用户
     *
     * @param user
     * @return
     */
    @AutoLog(value = "中台-用户管理-编辑", dataType = 2)
    @ApiOperation(value="中台-用户管理-编辑", notes="中台-用户管理-编辑")
    @RequestMapping(value = "/editMiddle", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<?> editMiddle(@RequestBody SysUser user) {
        sysUserService.editMiddleUser(user);
        return Result.OK("编辑成功!");
    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @GetMapping("/recycleBinMiddle")
    public Result recycleBinMiddle() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserType, 2);
        wrapper.in(SysUser::getRelTenantIds, TokenUtils.getLoginUser().getRelTenantIds());
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted(wrapper);
        return Result.ok(logicDeletedUserList);
    }

    /**
     * 根据中台用户ID查询绑定的商户id
     * @param userId
     * @return
     */
    @GetMapping("/queryBusinessIdByUserId")
    public Result queryBusinessIdByUserId(@RequestParam(name="userId",required=true) String userId) {
        return Result.ok(sysUserService.queryBusinessIdByUserId(userId));
    }
    //==========================================================中台====================================================


}
